# -*- coding: utf-8 -*-
# @Time : 2022/8/20 16:17
# @Author : WangYunfei
# @FileName: plt_font.py
# @Email: lxb_wyf@163.com
# 从字客网将woff文件转换为svg文件
import hashlib
import json
import zipfile

import requests


def get_svg(file_path):
    m = hashlib.md5()
    with open(file_path, 'rb') as fr:
        content = fr.read()
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
    }
    m.update(content)
    md5_text = m.hexdigest()
    # # 字客网
    # url = f'https://www.fontke.com/?g=Font&m=Tool&a=exists&toolId=convfont&md5={md5_text}'
    # res = requests.get(url)
    # res = json.loads(res.text)
    # print(res)
    # if res['exists'] == 'yes':
    url2 = 'https://www.fontke.com/tool/convfont/'
    # 并没有上传文件 而是文件的md5值，因此如果返回不存在，人工上传一次即可
    data = {
        'name': file_path.split('/')[-1].split('.')[0],
        'filemd5': md5_text,
        'oldFormat': 'woff',
        'newformats': 'svg',
    }
    res2 = requests.post(url2, data=data, headers=header)
    res2 = json.loads(res2.text)
    print(res2)
    down_url = 'https://www.fontke.com' + res2['downloadUrl']
    zip_res = requests.get(down_url, headers=header)
    with open('tmp.zip', 'wb') as fw:
        fw.write(zip_res.content)
    z = zipfile.ZipFile('./tmp.zip', 'r')
    for f in z.namelist():
        if 'svg' in f:
            return z.read(f).decode('utf-8')
    # else:
    #     print(res['exists'])


get_svg("ee552432.woff")
